package cn.tedu.csmall.passport.controller;

import cn.tedu.csmall.commons.consts.HttpConsts;
import cn.tedu.csmall.passport.pojo.dto.AdminLoginInfoDTO;
import cn.tedu.csmall.passport.pojo.param.AdminAddNewParam;
import cn.tedu.csmall.passport.pojo.param.AdminLoginInfoParam;
import cn.tedu.csmall.passport.pojo.param.AdminUpdateInfoParam;
import cn.tedu.csmall.passport.pojo.vo.AdminListItemVO;
import cn.tedu.csmall.commons.pojo.vo.PageData;
import cn.tedu.csmall.commons.security.LoginPrincipal;
import cn.tedu.csmall.passport.service.IAdminService;
import cn.tedu.csmall.commons.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 处理管理员相关请求的控制器
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@RestController
@RequestMapping("/admin")
@Api(tags = "01. 管理员管理模块")
@Slf4j
@Validated
public class AdminController {

    @Autowired
    private IAdminService adminService;

    // http://localhost:9181/admin/login
    @PostMapping("/login")
    @ApiOperation("管理员登录")
    @ApiOperationSupport(order = 10)
    public JsonResult<AdminLoginInfoDTO> login(AdminLoginInfoParam adminLoginInfoParam, @ApiIgnore HttpServletRequest request) {
        log.debug("开始处理【管理员登录】的请求，参数：{}", adminLoginInfoParam);
        String remoteAddr = request.getRemoteAddr();
        String userAgent = request.getHeader(HttpConsts.HEADER_USER_AGENT);
        AdminLoginInfoDTO loginInfo = adminService.login(adminLoginInfoParam, remoteAddr, userAgent);
        log.debug("即将响应：{}", loginInfo);
        return JsonResult.ok(loginInfo);
    }

    // http://localhost:9181/admin/logout
    @PostMapping("/logout")
    @ApiOperation("管理员退出登录")
    @ApiOperationSupport(order = 11)
    public JsonResult<Void> logout(@RequestHeader(HttpConsts.HEADER_AUTHORIZATION) String jwt) {
        log.debug("开始处理【管理员退出登录】的请求，参数：{}", jwt);
        adminService.logout(jwt);
        return JsonResult.ok();
    }

    // http://localhost:9181/admin/add-new
    @PostMapping("/add-new")
    @ApiOperation("添加管理员")
    @ApiOperationSupport(order = 100)
    @PreAuthorize("hasAuthority('/ams/admin/add-new')")
    public JsonResult addNew(@Valid AdminAddNewParam adminAddNewParam) {
        log.debug("开始处理【添加管理员】的请求，参数：{}", adminAddNewParam);
        adminService.addNew(adminAddNewParam);
        return JsonResult.ok();
    }

    // http://localhost:9181/admin/delete
    @PostMapping("/delete")
    @ApiOperation("根据ID删除管理员")
    @ApiOperationSupport(order = 200)
    @PreAuthorize("hasAuthority('/ams/admin/delete')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = true, dataType = "long")
    })
    public JsonResult delete(@Range(min = 1, message = "根据ID删除管理员失败，请提交合法的ID值！")
                             @RequestParam Long id) {
        log.debug("开始处理【根据ID删除管理员】的请求，参数：{}", id);
        adminService.delete(id);
        return JsonResult.ok();
    }

    // http://localhost:9181/admin/update
    @PostMapping("/update")
    @ApiOperation("修改管理员基本信息")
    @ApiOperationSupport(order = 300)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = true, dataType = "long")
    })
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    public JsonResult updateInfoById(@RequestParam @Range(min = 1, message = "请提交有效的管理员ID值！") Long id,
                                     @Valid AdminUpdateInfoParam adminUpdateInfoParam) {
        log.debug("开始处理【修改管理员基本信息】的业务，参数：{}", adminUpdateInfoParam);
        adminService.updateInfoById(id, adminUpdateInfoParam);
        return JsonResult.ok();
    }

    // http://localhost:9181/admin/update-password
    @PostMapping("/update-password")
    @ApiOperation("修改管理员密码")
    @ApiOperationSupport(order = 310)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = true, dataType = "long")
    })
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    public JsonResult updatePasswordById(@RequestParam @Range(min = 1, message = "请提交有效的管理员ID值！") Long id,
                                         @Valid String newPassword) {
        log.debug("开始处理【修改管理员管理员密码】的业务，参数：{}", newPassword);
        adminService.updatePasswordById(id, newPassword);
        return JsonResult.ok();
    }

    // http://localhost:9181/admin/list
    @GetMapping("/list")
    @ApiOperation("查询管理员列表")
    @ApiOperationSupport(order = 420)
    @PreAuthorize("hasAuthority('/ams/admin/read')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query")
    })
    public JsonResult list(@Range(min = 1, message = "查询管理员列表失败，请提供正确的页码值！") Integer page,
                           @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理【查询管理员列表】的请求，页码：{}", page);
        log.debug("当事人ID：{}", loginPrincipal.getId());
        log.debug("当事人用户名：{}", loginPrincipal.getUsername());
        if (page == null || page < 1) {
            page = 1;
        }
        PageData<AdminListItemVO> pageData = adminService.list(page);
        return JsonResult.ok(pageData);
    }

}
